package test;

/**
 * @author Marioszk
 * lettcode 2047
 * 有效单词数
 */
public class ValidToken_有效单词数 {

    public static void main(String[] args) {
        System.out.println(countValidWords2("!this  1-s b8d!"));
    }

    public static int countValidWords(String sentence) {
        String[] strArr = sentence.trim().split("\\s+");
        int count = 0;
        for (int i = 0; i < strArr.length; i++) {
            String token = strArr[i];
            if (!token.matches("([a-z]{1,}((-)?[a-z]{1,})?)?([!.,])?")) {
                continue;
            }
            if (token.indexOf("-") != token.lastIndexOf("-")) {
                continue;
            }

            if (token.contains(".") && token.indexOf(".") != token.lastIndexOf(".")) {
                continue;
            }
            if (token.contains("!") && token.indexOf("!") != token.lastIndexOf("!")) {
                continue;
            }
            if (token.contains(",") && token.indexOf(",") != token.lastIndexOf(",")) {
                continue;
            }
            count++;
        }

        return count;
    }

    public static int countValidWords2(String sentence) {
        int n = sentence.length();
        int l = 0, r = 0;
        int ret = 0;
        // 遍历句子
        while (true) {
            // 找出token的左右边界
            while (l < n && sentence.charAt(l) == ' ') {
                l++;
            }
            if (l >= n) {
                break;
            }
            r = l + 1;
            while (r < n && sentence.charAt(r) != ' ') {
                r++;
            }
            // 判断根据空格分解出来的 token 是否有效
            if (isValid(sentence.substring(l, r))) {
                ret++;
            }
            l = r + 1;
        }
        return ret;
    }

    public static boolean isValid(String word) {
        int n = word.length();
        // 是否有分隔符标识
        boolean hasHyphens = false;
        for (int i = 0; i < n; i++) {
            if (Character.isDigit(word.charAt(i))) {
                return false;
            } else if (word.charAt(i) == '-') {
                // 存在多个分隔符
                if (hasHyphens == true || i == 0 || i == n - 1 || !Character.isLetter(word.charAt(i - 1)) || !Character.isLetter(word.charAt(i + 1))) {
                    return false;
                }
                // 第一次置分隔符标识为真
                hasHyphens = true;
            } else if (word.charAt(i) == '!' || word.charAt(i) == '.' || word.charAt(i) == ',') {
                if (i != n - 1) {
                    return false;
                }
            }
        }
        return true;
    }
}
